package in.wenwen.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import in.wenwen.dto.ArticleDetailDto;
import in.wenwen.dto.ArticleDto;
import in.wenwen.dto.BlogDto;
import in.wenwen.handler.IndexHandler;
import in.wenwen.out.JSONStringOut;
import in.wenwen.out.TplOut;
import in.wenwen.service.IArticleService;
import in.wenwen.util.ConstUtil;
import in.wenwen.util.UserManage;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.util.StringUtil;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.RequestMapping;
import org.jiucheng.web.annotation.RequestMethod;
import org.jiucheng.web.util.WebUtil;

@Controller(IndexHandler.class)
public class ArticleController {
    
    @Inject
    private IArticleService articleService;
    
    @RequestMapping(value = {"/article/rnd/json", "/article/rnd.json"}, out = JSONStringOut.class)
    public List<BlogDto> rnd() {
        return articleService.getRnd(UserManage.getWebappId(), 12);
    }

    @RequestMapping(value = {"/blog/view/([0-9]+)", "/blog/view", "/blog/clazz", "/blog/clazz/([0-9]+)", "/search/tag"})
    public void blogView(String[] args) {
        WebUtil.redirect("/index?fr=".concat(args[0]));
    }
    
    @RequestMapping(value = "/article/([0-9]+)", method = RequestMethod.GET, out = TplOut.class)
    public String blog(String[] args, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ArticleDetailDto articleDetailDto = articleService.getArticleDetailDtoByCache(Long.parseLong(args[1]));
        ArticleDto articleDto;
        if(articleDetailDto == null || !UserManage.getWebappId().equals((articleDto = articleDetailDto.getArticleDto()).getWebappId())) {
            response.sendError(404);
            return null;
        }
        request.setAttribute("article", articleDto);
        List<String> tags = new ArrayList<String>();
        if(StringUtil.isNotBlank(articleDto.getTags())) {
            tags = Arrays.asList(articleDto.getTags().split(","));
        }
        request.setAttribute("tags", tags);
        request.setAttribute("prev", articleDetailDto.getPrev());
        request.setAttribute("next", articleDetailDto.getNext());
        return ConstUtil.getUri("article");
    }
}
